package com.example.demo.web;


import com.example.demo.entities.News;
import com.example.demo.service.NewService;
import com.example.demo.service.TagService;
import com.example.demo.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class IndexController {

    @Autowired
    private NewService newService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                Pageable pageable, Model model){
        model.addAttribute("page",newService.listNew(pageable));
        model.addAttribute("types",typeService.listTypeTop(3));
        model.addAttribute("tags",tagService.listTagTop(3));
        return "index";
    }

    //搜索
    @PostMapping("/search")
    public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,
                         @RequestParam String query, Model model){
        model.addAttribute("page",newService.listNew("%"+query+"%",pageable));
        model.addAttribute("query",query);
        return "search";
    }

    //展示点击的新闻
    @RequestMapping("/news/{id}")
    public String news(@PathVariable Long id, Model model){
        News news = newService.getAndConvert(id);
        model.addAttribute("news",news);
        return "new";
    }


}
